package cn.codeforfun.utils;

import cn.codeforfun.consts.RootConst;
import cn.codeforfun.consts.WeixinConst;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/2/16 0016.
 */
@Component
public class Long2ShortUtil {
    @Autowired
    private WeixinConst weixinConst;
    @Autowired
    private RootConst rootConstant;

    public String long2short(String url, Integer signId) throws IOException, WxErrorException {
        String longUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
                weixinConst.getAppid() + "&redirect_uri=" + URLEncoder.encode(url, "UTF-8") +
                "&response_type=code&scope=snsapi_base&state=" + signId + "#wechat_redirect";
        return updateToShort(longUrl);
    }

    public String updateToShort(String longUrl) {
        String httpUrl = "http://apis.baidu.com/3023/shorturl/shorten";
        String httpArg = null;
        try {
            httpArg = "url_long=" + URLEncoder.encode(longUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String jsonResult = request(httpUrl, httpArg);
        Map<String, Object> decode = null;
        try {
            decode = JsonUtils.decode(jsonResult, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String shortUrl = (String) ((Map) ((List) decode.get("urls")).get(0)).get("url_short");
        return shortUrl;
    }

    /**
     * @param httpUrl :请求接口
     * @param httpArg :参数
     * @return 返回结果
     */
    public String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey", rootConstant.getApikey());
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
